package projectmanagement.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import projectmanagement.model.Task;
import projectmanagement.model.dao.TaskDao;

@Transactional
public class TaskDaoImpl implements TaskDao{
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	private EntityManager em;
	
	@PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
	
	public List<Task> getTaskList() {
		logger.info("Getting task list!");
		
        List<Task> resultList = em.createQuery("select t from Task t").getResultList();
		return resultList;
	}	
	
	public List<Task> getTaskListByAssignee(String username) {
		logger.info("Getting task list by username:" + username);
		List<Task> resultList = em.createQuery("select t from Task t, Person p where p.id = t.assignee and p.username=:username").setParameter("username", username).getResultList();
		return resultList;
	}
	
	public Task getTaskById(int id) {
		logger.info("Getting task by id: " + id);
		
		return em.find(Task.class, id);
	}

	public void save(Task task) {
		logger.info("Saving task..");
		
		if (task.getId() == 0) {
            // new
            em.persist(task);
        } else {
            // update
            em.merge(task);
        }
	}
	
	public void remove(int id) {
		logger.info("Deleting task..");
		
		Task task  = getTaskById(id);
	        if (task != null) {
	            em.remove(task);
	        } 
	}

}
